package userPages;
import pages.*;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import templates.Template;
import database.DBUtils;

/**
 * Servlet implementation class AddResevation
 */
public class AddReservation extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AddReservation() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			Template template = new Template("user_templates\\user_add_reservation");

			addInstrumentTypes(template,  request.getUserPrincipal().getName());
			addTimeSlots(template);
			// template.addChange("rows", "");
			response.getOutputStream().print(
					template.createPage(
							"Instruments Labaratory: Add Resrvation", LMUtils
									.getUserLogin(request)));
		} catch (Exception e) {
			try {
				String userLogin = LMUtils.getUserLogin(request);
				response.getWriter().print(
						ErrorPage.generateErrorPage(e.getMessage(), userLogin));
			} catch (InternalErrorException e1) {
				response.getWriter().print(e1.getMessage());
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

	}

	/**
	 * Add available for user types of instruments
	 * @param template
	 * @param username
	 */
	private void addInstrumentTypes(Template template, String username) {

		//System.out.println("Hello");
		String typesOption = "<option value=\"0\">Unknown</option>\n";
		Connection conn = null;
		PreparedStatement selectUserStmt = null;
		ResultSet rs = null;
		try {
			conn = DBUtils.getConnection();
			//System.out.println(username);
			selectUserStmt = conn
					.prepareStatement("select i.id, i.name from instrumenttypes as i, permissions as p where p.userlogin=? && p.typeid=i.id;");
			selectUserStmt.setString(1, username);
			rs = selectUserStmt.executeQuery();
			if (rs == null) {
				//System.out.println("fail1");
			} else {
				//System.out.println("success1");
				while (rs.next()) {
					//System.out.println("success");
					typesOption += "<option value=\"" + rs.getString("id")
							+ "\">"
							+ rs.getString("name") + "</option>\n";

				}
			}

		} catch (Exception e) {
			//System.out.println("fail12 " + e.getMessage());
		} finally {
			DBUtils.close(rs);
			DBUtils.close(selectUserStmt);
			DBUtils.close(conn);
		}

		template.addChange("instrument_types", typesOption);
	}

	/**
	 * Add timeslots (now it is always 15 min)
	 * @param template
	 */
	private void addTimeSlots(Template template) {
		// TODO: Get Time Slot (in minutes)
		int timeSlot = 15;
		Calendar calendar = new GregorianCalendar(2010, Calendar.JANUARY, 1);
		Calendar stop = new GregorianCalendar(2010, Calendar.JANUARY, 2);
		String timeOptions = "";
		int slotId = 0;
		Format formatter = new SimpleDateFormat("HH:mm");
		while (calendar.before(stop)) {
			if(formatter.format(calendar.getTime()).compareTo("12:00") == 0){
				timeOptions += "<option value=\""
					+ formatter.format(calendar.getTime()) + "\"  selected=\"selected\">"
					+ formatter.format(calendar.getTime()) + "</option>\n";
			}
			else
			{
			timeOptions += "<option value=\""
					+ formatter.format(calendar.getTime()) + "\">"
					+ formatter.format(calendar.getTime()) + "</option>\n";
			}
			
			slotId++;
			calendar.add(Calendar.MINUTE, timeSlot);
		}

		template.addChange("instruments_slots", timeOptions);
		Calendar currDate = Calendar.getInstance();
		formatter = new SimpleDateFormat("dd/MM/yy");
		template.addChange("currentDate", formatter.format(currDate.getTime()));

	}

}
